package com.bb.blog.security.service.wx;

import com.sun.jndi.toolkit.url.Uri;
import org.springframework.http.HttpMethod;
import org.springframework.http.RequestEntity;

import java.net.URI;
import java.net.URISyntaxException;
import java.text.Format;
import java.text.MessageFormat;

public class WxRequestFactory {
    private String wxBaseUrl = "https://api.weixin.qq.com";
    private String appid = "";
    private String appSecret;

    RequestEntity accessToken(){
        String template = "?grant_type=client_credential&appid={0}&secret={1}";
        String queryString = MessageFormat.format(template,appid,appSecret);

        try {
            URI uri = new URI(wxBaseUrl + WxApi.accessToken + queryString);
            RequestEntity requestEntity = new RequestEntity(HttpMethod.GET,uri);
            return requestEntity;
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        return null;

    }

    RequestEntity codeToSession(String code){
        String template = "?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code";
        String queryString = MessageFormat.format(template,appid,appSecret,code);
        try{
            URI uri = new URI(wxBaseUrl + WxApi.codeToSession + queryString);
            RequestEntity requestEntity = new RequestEntity(HttpMethod.GET, uri);
            return requestEntity;
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        return null;
    }
}
class WxApi{
    public static final String accessToken = "/cgi-bin/token";
    public static final String codeToSession = "/sns/jscode2session";
}
